//
//  KY_VideoListViewController.m
//  ShaQueVideo
//
//  Created by huliang on 13-4-26.
//  Copyright (c) 2013年 科悦信达. All rights reserved.
//

#import "KY_VideoListViewController.h"
#import "KY_VideoDetailViewController.h"
#import "KY_WeiBoActionSheet.h"
#import "KY_AppDelegate.h"
@implementation KY_VideoListViewController
@synthesize adView;
#pragma ------asiDelegate
-(void)requestFailed:(ASIHTTPRequest *)request
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
-(void)requestFinished:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    if (!error) {

        NSDictionary *updateDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"update"];
        NSMutableDictionary *m_dic = [NSMutableDictionary dictionaryWithDictionary:updateDic];

        [m_dic removeObjectForKey:self.cid];
        [m_dic setObject:@"0" forKey:self.cid];
        [[NSUserDefaults standardUserDefaults] setObject:m_dic forKey:@"update"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        NSDictionary *timeDictionary = [[NSUserDefaults standardUserDefaults] objectForKey:@"newTime"];
        NSMutableDictionary *time_dic = [NSMutableDictionary dictionaryWithDictionary:timeDictionary];

        [time_dic removeObjectForKey:self.cid];
        NSDate *date = [NSDate date];
        NSTimeInterval time = [date timeIntervalSince1970];
        NSString *timeString = [NSString stringWithFormat:@"%f",time];
        [time_dic setObject:timeString forKey:self.cid];
        [[NSUserDefaults standardUserDefaults] setObject:time_dic forKey:@"newTime"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        NSString *response = [request responseString];
        self.listArr = [response objectFromJSONString];
        NSLog(@"%@",self.listArr);
        [self.tableView reloadData];
    }

}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
//    if (!error) {
//        
//        NSDictionary *updateDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"update"];
//        NSMutableDictionary *m_dic = [NSMutableDictionary dictionaryWithDictionary:updateDic];
//        
//        [m_dic removeObjectForKey:self.cid];
//        [m_dic setObject:@"0" forKey:self.cid];
//        [[NSUserDefaults standardUserDefaults] setObject:m_dic forKey:@"update"];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        
//        NSDictionary *timeDictionary = [[NSUserDefaults standardUserDefaults] objectForKey:@"newTime"];
//        NSMutableDictionary *time_dic = [NSMutableDictionary dictionaryWithDictionary:timeDictionary];
//
//        [time_dic removeObjectForKey:self.cid];
//        NSDate *date = [NSDate date];
//        NSTimeInterval time = [date timeIntervalSince1970];
//        NSString *timeString = [NSString stringWithFormat:@"%f",time];
//        [time_dic setObject:timeString forKey:self.cid];
//        [[NSUserDefaults standardUserDefaults] setObject:time_dic forKey:@"newTime"];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        
//        NSString *response = [request responseString];
//        self.listArr = [response objectFromJSONString];
//        NSLog(@"%@",self.listArr);
//        [self.tableView reloadData];
//    }

}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if( self.adView !=nil && self.adView.superview !=nil ){
        [self.adView removeFromSuperview];
    }
    self.adView = [AdViewView requestAdViewViewWithDelegate:self];
    [self.view addSubview:self.adView];
}


-(void)loadData{
    
    switch ([self.cid  intValue]) {
        case 13:
            self.title = @"杯具了";
            break;
        case 14:
            self.title = @"碉堡了";
            break;
        case 15:
            self.title = @"傻缺美女";
            break;
        case 16:
            self.title = @"傻缺小孩";
            break;
        case 17:
            self.title = @"恶搞";
            break;
        case 18:
            self.title = @"傻缺动物";
            break;
        default:
            break;
    }
    self.listArr = [NSArray array];
    
    [self showBackBtn];
    NSString *url = [NSString stringWithFormat:@"%@?cid=%@",URL_DETAIL_INFO,self.cid];
    self.dataRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    
    [self.dataRequest setDelegate:self];
    [self.dataRequest startAsynchronous];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.dataRequest cancel];
    [self.dataRequest setDelegate:nil];
     self.dataRequest = nil;
    [self.adView removeFromSuperview];
    [self.adView setDelegate:nil];
     self.adView = nil;

}
- (NSString*) adViewApplicationKey {
    
    return @"SDK201312081206290g605c5qaeugil1";
    // 在 AdView 网站申请的 key.

}
- (UIViewController*) viewControllerForPresentingModalView {

//    KY_AppDelegate *delegate =  [[UIApplication sharedApplication] delegate];
//    
//    return  delegate.tabBarController;
//     
    return self;
        // 全屏⼲⼴广告附着的控制器.
}
- (BOOL) adViewTestMode {


        return NO;
    //在测试时返回 YES;

}
- (void)viewDidLoad
{
    [super viewDidLoad];

    switch ([self.cid  intValue]) {
        case 13:
            self.title = @"杯具了";
            break;
        case 14:
            self.title = @"碉堡了";
            break;
        case 15:
            self.title = @"傻缺美女";
            break;
        case 16:
            self.title = @"傻缺小孩";
            break;
        case 17:
            self.title = @"恶搞";
            break;
        case 18:
            self.title = @"傻缺动物";
            break;
        default:
            break;
    }
    self.listArr = [NSArray array];


    [self showBackBtn];
    NSString *url = [NSString stringWithFormat:@"%@?cid=%@",URL_DETAIL_INFO,self.cid];
    self.dataRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    
    [self.dataRequest setDelegate:self];
    [self.dataRequest startAsynchronous];


    [self.view setBackgroundColor:GLOBAL_VIEW_BG_COLOR];
    
}
-(void)backBtnClicked:(id)sender
{

if( [self.navigationController popViewControllerAnimated:YES]  == nil){
    [self dismissModalViewControllerAnimated:YES];
}

    if( [self.navigationController popViewControllerAnimated:YES]  == nil){
        [self dismissModalViewControllerAnimated:YES];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

/**
 * 成功收到广告的回调方法。
 */
- (void)adViewDidReceiveAd:(AdViewView *)adViewView{
    
    [UIView animateWithDuration:0.6  animations:^{
        [self.tableView setFrame:CGRectMake(0, self.adView.frame.size.height, 320, self.view.frame.size.height-self.adView.frame.size.height)];
    }];
}

#pragma mark - TableView Delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSDictionary *dict = [self.listArr objectAtIndex:indexPath.row];
    KY_VideoDetailViewController *detailView = [[KY_VideoDetailViewController alloc] initWithVideoURL:[dict objectForKey:@"playurl"]];
    [self.navigationController presentModalViewController:detailView animated:YES];
    [detailView release];
    NSArray *historyArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"history"];
    NSString *playUrl = [[self.listArr objectAtIndex:indexPath.row] objectForKey:@"playurl"];
    
    for (NSDictionary *dic in historyArray) {
        
        if ([[dic objectForKey:@"playurl"] isEqualToString:playUrl]) {
            return;
        }
    }
    NSMutableArray *m_array = [NSMutableArray arrayWithArray:historyArray];
    [m_array addObject:[self.listArr objectAtIndex:indexPath.row]];
    [[NSUserDefaults standardUserDefaults] setObject:m_array forKey:@"history"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 124;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [self.listArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identify = @"detaillistcell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if(cell == nil){
        NSArray *nibArr = [[NSBundle mainBundle] loadNibNamed:@"KY_VideoListTableCell" owner:self options:nil];
        cell = (UITableViewCell *)[ nibArr objectAtIndex:0];
    }
    
    UIImageView *img;  UITextView *descTextView;  NSDictionary *dict;

    dict = [self.listArr objectAtIndex:indexPath.row];
   // UIView  *bgView = (UIImageView *)[cell viewWithTag:1];
//    if( (indexPath.row % 2) != 0){
//        bgView.hidden = NO;
//    }else{
//        bgView.hidden = YES;
//    }
    UIButton *shareBtn = (UIButton *)[cell viewWithTag:99];
    shareBtn.accessibilityValue =  [NSString stringWithFormat:@"%d",indexPath.row];
    [shareBtn addTarget:self action:@selector(shareWeiBo:) forControlEvents:UIControlEventTouchUpInside];

    UIButton *shoucangBtn = (UIButton *)[cell viewWithTag:98];
    NSString *playUrl = [[self.listArr objectAtIndex:indexPath.row] objectForKey:@"playurl"];
    NSArray *m_array = [[NSUserDefaults standardUserDefaults] objectForKey:@"favourite"];
    
    for (NSDictionary *dic in m_array) {
        
        if ([[dic objectForKey:@"playurl"] isEqualToString:playUrl]) {
            
            [shoucangBtn setTitle:@"已收藏" forState:UIControlStateNormal];
            shoucangBtn.selected = YES;
             shoucangBtn.tag = 89;
             break;
        }
    }

    shoucangBtn.accessibilityValue = [NSString stringWithFormat:@"%d",indexPath.row];
    [shoucangBtn addTarget:self action:@selector(collectVideo:) forControlEvents:UIControlEventTouchUpInside];
    
    img = (UIImageView *)[cell viewWithTag:11];
    NSURL *url = [NSURL URLWithString:[dict objectForKey:@"icon"]];
    [img setImageWithURL:url placeholderImage:nil];
    
    descTextView = (UITextView *)[cell viewWithTag:10];
    descTextView.text = [dict objectForKey:@"title"];
    
    return cell;
}
-(void)collectVideo:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSArray *Farray = [[NSUserDefaults standardUserDefaults] objectForKey:@"favourite"];
    if (button.tag == 98) {

        NSMutableArray *m_array = [NSMutableArray arrayWithArray:Farray];
        [m_array addObject:[self.listArr objectAtIndex:[button.accessibilityValue intValue]]];
        
        [[NSUserDefaults standardUserDefaults] setObject:m_array forKey:@"favourite"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [button setTitle:@"已收藏" forState:UIControlStateNormal];
        button.selected = YES;
        button.tag = 89;
    }
    else if(button.tag == 89)
    {
        NSMutableArray *m_array = [NSMutableArray arrayWithArray:Farray];

        for (NSDictionary *dic in m_array) {

            if ([[dic objectForKey:@"playurl"] isEqualToString:[[self.listArr objectAtIndex:[button.accessibilityValue intValue]] objectForKey:@"playurl"]]) {

                [m_array removeObject:dic];
                break;
            }
        }
        
        [[NSUserDefaults standardUserDefaults] setObject:m_array forKey:@"favourite"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [button setTitle:@"收藏" forState:UIControlStateNormal];
        button.selected = NO;
        button.tag = 98;
    }
}

-(void)shareWeiBo:(id)sender{

    UIButton *button = (UIButton *)sender;
    self.sharedNum = [button.accessibilityValue intValue];
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择设备"  delegate:self
                                                  cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];

        [sheet addButtonWithTitle:@"分享到新浪微博"];
        [sheet addButtonWithTitle:@"分享到微信"];
        [sheet addButtonWithTitle:@"分享到朋友圈"];
        [sheet addButtonWithTitle:@"取消"];
        sheet.cancelButtonIndex = sheet.numberOfButtons-1;
        // [sheet addButtonWithTitle:@"本地播放"];
        [sheet showFromRect:self.view.bounds inView:self.tabBarController.view animated:YES];

}
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{



        if (buttonIndex == 0) {

             
            SinaWeibo *sinaweibo = [self sinaweibo];
            [sinaweibo logIn];


        }
        else if (buttonIndex == 1)
        {
            KY_AppDelegate *delegate =  [[UIApplication sharedApplication] delegate];
            delegate.sinaOrWeixin = YES;
            _scene = WXSceneSession;

            [self sendVideoContent];
        }
        else if (buttonIndex == 2)
        {
            KY_AppDelegate *delegate =  [[UIApplication sharedApplication] delegate];

            delegate.sinaOrWeixin = YES;
            _scene = WXSceneTimeline;
            
            [self sendVideoContent];
        }
        
        
}
- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];

    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}
- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    [self storeAuthData];
    TextViewController *viewController = [[TextViewController alloc] init];
    NSString *str = [NSString stringWithFormat:@"不看是你的损失哦！！！%@ %@",[[self.listArr objectAtIndex:self.sharedNum] objectForKey:@"title"],[[self.listArr objectAtIndex:self.sharedNum] objectForKey:@"sourceurl"]];
    viewController.m_nsLastText = str;
    UINavigationController *navigatitonController = [[[UINavigationController alloc]initWithRootViewController:viewController] autorelease];
	[self presentModalViewController:navigatitonController animated:YES];
    
}

-(void) sendVideoContent
{
    WXMediaMessage *message = [WXMediaMessage message];
    NSDictionary *dic = [self.listArr objectAtIndex:self.sharedNum];
    message.title = @"超欢乐的视频，不看是你的损失哦";

     message.description = [dic objectForKey:@"title"];
    NSURL *url = [NSURL URLWithString:[dic objectForKey:@"icon"]];
    [message setThumbImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:url]]];
    
    WXVideoObject *ext = [WXVideoObject object];
    NSString *videoString = [[NSString alloc] initWithString:[dic objectForKey:@"playurl"]];
    [videoString stringByReplacingOccurrencesOfString:@" " withString:@""];
    ext.videoUrl =  videoString;
    [videoString release];
    //@"http://www.tudou.com/programs/view/6vx5h884JHY/?fr=1"
    message.mediaObject = ext;
    SendMessageToWXReq* req = [[[SendMessageToWXReq alloc] init]autorelease];
    req.bText = NO;
    req.message = message;
    req.scene = _scene;
    [WXApi sendReq:req];
}
- (SinaWeibo *)sinaweibo
{
    KY_AppDelegate  *delegate = (KY_AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.sinaweibo.delegate = self;
    return delegate.sinaweibo;
}



@end
